A string consisting of lowercase Latin letters is
given. Sort its letters in ascending and then in descending lexicographical
order.
Input. One line that contains no more than 100 lowercase
Latin letters 'a' - 'z'.
Output. In the first line, output the sorted input string in
non-decreasing order of its ASCII codes. In the second line, output the sorted
input string in non-increasing order of its ASCII codes.
Sample input |
Sample output |
qwerty |
eqrtwy ywtrqe |
strings
Sort the strings using sort function from STL. Use the comparator less<int>() for
sorting in increasing order and comparator greater<int>() for sorting in decreasing order.
Algorithm
realization
Declare the character array.
#define MAX 101
char s[MAX];
Read the string.
gets(s);
Sort the letters in
increasing order. Print the resulting string.
sort(s,s+strlen(s),less<int>());
puts(s);
Sort the letters in
decreasing order. Print the resulting string.
sort(s,s+strlen(s),greater<int>());
puts(s);
Algorithm
realization – string
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s;
int main(void)
{
cin >> s;
sort(s.begin(),s.end(),less<int>());
cout << s << "\n";
sort(s.begin(),s.end(),greater<int>());
cout << s << "\n";
return 0;
}
Algorithm
realization – C, swap
sort
#include <stdio.h>
#include <string.h>
char s[101], temp;
int i, j, n;
int main(void)
{
gets(s);
n = strlen(s);
for (i = 0; i <
n; i++)
for (j = i + 1; j
< n; j++)
if (s[i] >
s[j])
{
temp = s[i]; s[i] = s[j];
s[j] = temp;
}
puts(s);
for (i = 0; i <
n; i++)
for (j = i + 1; j
< n; j++)
if (s[i] <
s[j])
{
temp = s[i]; s[i] = s[j];
s[j] = temp;
}
puts(s);
return 0;
}
Java realization
import
java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new
Scanner(System.in);
String s[] = con.nextLine().split("");
// s =
{"q", "w", "e", "r", "t",
"y"}
Arrays.sort(s);
System.out.println(String.join("", s));
Arrays.sort(s,Collections.reverseOrder());
System.out.println(String.join("", s));
con.close();
}
}
Python realization
s = input()
print(''.join(sorted(s)))
print(''.join(sorted(s, reverse = True)))
Python realization – sorting
l = list(input())
l.sort()
print(''.join(l))
l.sort(reverse = True)
print(''.join(l))